﻿using MedicalManagementAPP.AccountModule;
using MedicalManagementAPP.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MedicalManagementAPP.Forms.DocForms
{
    public partial class PrescribeMedicineForm : Form
    {
        public Person doc;
        private String[][] medicineTypes;

        private string selectedMedicineName; // 当前被选中的药品名称
        private string selectedMedicineID; // 当前被选中的药品ID

        public PrescribeMedicineForm(ref Person doc)
        {
            InitializeComponent();
            this.doc = doc;
            medicineTypes = MedicineManager.GetMedicineTypes();
            initTree();
            initMedicineListView();
            initCurRecordSetListView();
            initRecentRecord();
        }
        private void initTree()
        {
            // 处方药
            foreach (string i in medicineTypes[0])
            {
                treeView1.Nodes[0].Nodes.Add(i);
            }
            // 非处方药
            foreach (string i in medicineTypes[1])
            {
                treeView1.Nodes[1].Nodes.Add(i);
            }
        }

        private void initMedicineListView()
        {
            // MedicineID,Stock,Price,Mtype,MName,MUnit from Medicines
            medicineListView.Columns.Add("药品ID");
            medicineListView.Columns[0].Width = 50;
            medicineListView.Columns.Add("药品名称");
            medicineListView.Columns[1].Width = 100;
            medicineListView.Columns.Add("药品价格");
            medicineListView.Columns[2].Width = 60;
            medicineListView.Columns.Add("药品单位");
            medicineListView.Columns[3].Width = 60;
            medicineListView.Columns.Add("药品存量");
            medicineListView.Columns[4].Width = 60;
        }

        private void initCurRecordSetListView()
        {
            // MedicineID,MName,Price,MUnit,Amount，Amount*Price from Medicines,MedicalRecords
            curRecordSetListView.Columns.Add("药品ID");
            curRecordSetListView.Columns[0].Width = 50;
            curRecordSetListView.Columns.Add("药品名称");
            curRecordSetListView.Columns[1].Width = 100;
            curRecordSetListView.Columns.Add("药品单价");
            curRecordSetListView.Columns[2].Width = 60;
            curRecordSetListView.Columns.Add("药品单位");
            curRecordSetListView.Columns[3].Width = 60;
            curRecordSetListView.Columns.Add("药品用量");
            curRecordSetListView.Columns[4].Width = 60;
            curRecordSetListView.Columns.Add("当前药品价格");
            curRecordSetListView.Columns[5].Width = 100;
            curRecordSetListView.Columns.Add("记录ID");
            curRecordSetListView.Columns[6].Width = 50;
        }
        private void initRecentRecord()
        {
            // PatientName,RecordSetID,RecordDate
            // 加载近期病历
            DataTable data = RecordSetManager.GetRecentRecord();
            recentListView.Items.Clear();
            foreach (DataRow row in data.Rows)
            {
                ListViewItem item = new ListViewItem(row[0].ToString());
                item.SubItems.Add(row[1].ToString());
                item.SubItems.Add(row[2].ToString());
                recentListView.Items.Add(item);
            }
        }
        /// <summary>
        /// 根据treeView1中选择的药品种类将药品信息加载到medicineListView中
        /// </summary>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string selectedType = treeView1.SelectedNode.Text;
            if(selectedType == "处方药" || selectedType == "非处方药") { return; }

            DataTable data = MedicineManager.GetMedicineByType(selectedType);
            medicineListView.Items.Clear();
            // 数据库：0 MedicineID,1 Stock,2 Price,3 Mtype,4 MName,5 MUnit
            // ListView顺序：ID、名称、价格、单位、存量
            foreach (DataRow row in data.Rows)
            {
                ListViewItem item = new ListViewItem();
                item.Text = row[0].ToString();
                item.SubItems.Add(row[4].ToString());
                item.SubItems.Add(row[2].ToString());
                item.SubItems.Add(row[5].ToString());
                item.SubItems.Add(row[1].ToString());
                medicineListView.Items.Add(item);
            }
        }

        /// <summary>
        /// 更新选中的药品ID和名字到类的private变量中
        /// </summary>
        private void medicineListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (medicineListView.SelectedItems.Count < 1) { return; }
            // 更新选中的药品ID和名字
            selectedMedicineName = medicineListView.SelectedItems[0].SubItems[1].Text;
            selectedMedicineID = medicineListView.SelectedItems[0].SubItems[0].Text;

            medicineNameTextBox.Text = selectedMedicineName;
        }

        /// <summary>
        /// 根据输入的病历ID自动读取病历内的药品
        /// </summary>
        private void recordSetIDTextBox_TextChanged(object sender, EventArgs e)
        {
            curRecordSetListView.Items.Clear();
            if (recordSetIDTextBox.Text == "") { return; }
            string recordSetID = recordSetIDTextBox.Text;
            // MedicineID,MName,Price,MUnit,Amount，Amount*Price from Medicines,MedicalRecords
            string sql = "select M.MedicineID,MName,Price,MUnit,MedicineAmount,MedicineAmount*Price TotalPrice,MR.RecordID from Medicines M,MedicalRecords MR where RecordSetID=@id and M.MedicineID=MR.MedicineID";
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@id",recordSetID)
            };
            DataTable data = Connection.SqlQuery(sql, parameters);
            if (data == null || data.Rows.Count < 1) { return; }
            curRecordSetListView.Items.Clear();
            foreach (DataRow row in data.Rows)
            {
                ListViewItem item = new ListViewItem();
                item.Text = row[0].ToString();
                item.SubItems.Add(row[1].ToString());
                item.SubItems.Add(row[2].ToString());
                item.SubItems.Add(row[3].ToString());
                item.SubItems.Add(row[4].ToString());
                item.SubItems.Add(row[5].ToString());
                item.SubItems.Add(row[6].ToString());
                curRecordSetListView.Items.Add(item);
            }
            showTotalPrice();
        }

        /// <summary>
        /// 刷新药品类别和病历的药品列表
        /// </summary>
        private void refreshListViews()
        {
            if (treeView1.SelectedNode != null) { treeView1_AfterSelect(null, null); }// 刷新药品列表
            recordSetIDTextBox_TextChanged(null,null);// 刷新病历列表
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            if (recordSetIDTextBox.Text == "") { MessageBox.Show("请输入病历号"); return; }
            if (medicineListView.SelectedItems.Count != 1) { MessageBox.Show("请在上方选择一个药品");return; }
            if (medicineNumericUpDown.Value < 1) { MessageBox.Show("请输入正确的药品数量");return; }

            int stock = int.Parse(medicineListView.SelectedItems[0].SubItems[4].Text);
            int useAmount = (int)medicineNumericUpDown.Value;
            if (stock < useAmount) { MessageBox.Show("药品存量不足");return; }

            string sql = "insert into MedicalRecords (RecordSetID,MedicineID,MedicineAmount) " +
                "VALUES(@RID,@MID,@Amount)";
            SqlParameter[] parameter = new SqlParameter[]
            {
                new SqlParameter("@RID",recordSetIDTextBox.Text),
                new SqlParameter("@MID",selectedMedicineID),
                new SqlParameter("@Amount",useAmount)
            };
            if(!Connection.SqlNoQuery(sql, parameter)) { MessageBox.Show("执行失败\n错误发生在插入药品记录到病历阶段");return; }

            sql = "update Medicines set Stock=@newStock where MedicineID=@MID";
            parameter = new SqlParameter[]
            {
                new SqlParameter("@newStock",stock-useAmount),
                new SqlParameter("@MID",selectedMedicineID)
            };
            if(!Connection.SqlNoQuery(sql, parameter)) { MessageBox.Show("执行失败\n错误发生在修改药品存量阶段"); return; }

            showTotalPrice();
            refreshListViews();
            MessageBox.Show("插入成功");
        }

        private void delButton_Click(object sender, EventArgs e)
        {
            if (curRecordSetListView.SelectedItems.Count != 1) { MessageBox.Show("请在左侧选择一条需要删除的数据");return; }
            string sql = "delete from MedicalRecords where RecordID=@RID";
            string RID = curRecordSetListView.SelectedItems[0].SubItems[6].Text;
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@RID",RID)
            };
            if (!Connection.SqlNoQuery(sql, parameters)) { MessageBox.Show("删除失败\n错误发生在删除阶段");return; }

            int amount = int.Parse(curRecordSetListView.SelectedItems[0].SubItems[6].Text);
            string MID = curRecordSetListView.SelectedItems[0].SubItems[0].Text;
            sql = "update Medicines set stock=stock+@amount where MedicineID=@MID";
            parameters = new SqlParameter[]
            {
                new SqlParameter("@amount",amount),
                new SqlParameter("@MID",MID)
            };
            if (!Connection.SqlNoQuery(sql, parameters)) { MessageBox.Show("删除失败\n错误发生在重新加入药品数量阶段"); return; }

            refreshListViews();
            showTotalPrice();
            MessageBox.Show("删除成功");
        }

        /// <summary>
        /// 将药品总价格放在priceLabel中
        /// </summary>
        private void showTotalPrice()
        {
            if (curRecordSetListView.Items.Count < 1) { priceLabel.Text = "总价格：0 元"; return; }
            double price=0;
            foreach(ListViewItem i in curRecordSetListView.Items)
            {
                price += double.Parse(i.SubItems[5].Text);
            }

            priceLabel.Text = "总价格：" + price.ToString() +" 元";
        }

        private void recentListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (recentListView.SelectedItems.Count != 1) { return; }
            recordSetIDTextBox.Text = recentListView.SelectedItems[0].SubItems[1].Text;
        }

        private void label6_Click(object sender, EventArgs e)
        {
            initRecentRecord();
        }
    }
}
